package com.example.su_shi_tan_home.child

import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.fastjson.JSON
import com.example.library_common.utils.normalShortToast
import com.example.su_shi_tan_bas_lib.adapter.ab_list_adapter.CommonAdapter
import com.example.su_shi_tan_bas_lib.adapter.ab_list_adapter.CommonViewHolder
import com.example.su_shi_tan_bas_lib.base.BaseLazyDataBindingFragment
import com.example.su_shi_tan_bas_lib.bean.CommonBean
import com.example.su_shi_tan_bas_lib.bean.DataCacheModule
import com.example.su_shi_tan_bas_lib.cache.JssCacheManager
import com.example.su_shi_tan_bas_lib.networking.RestClient
import com.example.su_shi_tan_bas_lib.utils.even.MessageWrap
import com.example.su_shi_tan_bas_lib.utils.even.TO_REFRESH_USER_SIGN_USER_INFO
import com.example.su_shi_tan_core.arouter.HomeARouter
import com.example.su_shi_tan_core.constant.SignUserBeanHolder
import com.example.su_shi_tan_home.R
import com.example.su_shi_tan_home.bean.SignConfigBean
import com.example.su_shi_tan_home.databinding.LightingAllFragmentBinding
import com.senon.modularapp.util.JssSpannableString
import java.text.DecimalFormat

/**
 *签到积分（全部）
 *
 * */
@Route(path = HomeARouter.LightingAllFragment)
class LightingAllFragment : BaseLazyDataBindingFragment<LightingAllFragmentBinding>() {


    private val Save_TAG =HomeARouter.LightingAllFragment

    override fun layoutId(): Int {
        return R.layout.lighting_all_fragment
    }


    private var mSignConfigAdapter: CommonAdapter<SignConfigBean>? = null

    private var mData= mutableListOf<SignConfigBean>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mSuperBackPressedSupport = false


    }

    override fun initView(view: View) {
        view.setBackgroundColor(Color.TRANSPARENT)
        Log.d("initView", "initView: ")
        mSignConfigAdapter = object : CommonAdapter<SignConfigBean>(
            _mActivity,
            mData,
            R.layout.lighting_all_sign_config_item_fragment
        ) {
            override fun convert(helper: CommonViewHolder?, item: SignConfigBean?, position: Int) {
                val signNum = SignUserBeanHolder.getSignUser()?.sign_num ?: 0

                val unSigned = (position+1) > signNum

                helper?.setText(R.id.dayNum, item?.day)
                    ?.setViewVisblies(R.id.signedLayout, if (unSigned) View.GONE else View.VISIBLE)
                    ?.setViewVisblies(R.id.unSigned, if (unSigned) View.VISIBLE else View.GONE)
                    ?.setText(R.id.jiFenTv, "+${item?.sign_num}")
                    ?.setText(R.id.signedTv, "+${item?.sign_num}")
            }

        }
        viewBinder.mSignConfigGridView.adapter = mSignConfigAdapter
    }

    override fun handMessage(msg: MessageWrap?) {
//        super.handMessage(msg)
        when (msg?.message) {
            TO_REFRESH_USER_SIGN_USER_INFO -> {
                allSigned()
            }
        }
    }

    private fun allSigned() {
        val signNum = SignUserBeanHolder.getSignUser()?.sum_sgin_day
        val format = DecimalFormat("0000")
        val convertSuffix = convertSuffix(format.format(signNum))
        viewBinder.dayCount.text = JssSpannableString(_mActivity, convertSuffix)
            .first(convertSuffix)
            .textColor(R.color.text_color_1)
            .backgroundColor(R.color.PrimaryColor)
            .all("\t")
            .backgroundColor(R.color.bg_color_0)
    }

    private fun convertSuffix(suffix: String): String {
        val mCharArray = suffix.toCharArray()
        val stringBuilder = StringBuilder()
        for ((index, e) in mCharArray.withIndex()) {
            if (index != mCharArray.size - 1) {
                stringBuilder.append(" ").append(e).append(" ").append("\t\t")
            } else {
                stringBuilder.append(" ").append(e).append(" ")
            }
        }
        return stringBuilder.toString()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        val bean  = CommonBean<List<SignConfigBean>>()
        bean.data=mData

        val dataCacheModule = DataCacheModule()

        dataCacheModule.beanList.addAll(mData)


        outState.putString("Save_TAG", Save_TAG)

        JssCacheManager.save(Save_TAG, dataCacheModule)
    }

    override fun onViewStateRestored(savedInstanceState: Bundle?) {
        super.onViewStateRestored(savedInstanceState)

        allSigned()

        JssCacheManager.getCache(Save_TAG) { o: Any ->

            if (o is DataCacheModule) {
                mData.clear()
                val beanList = o.beanList

                for (e in beanList) {
                    mData.add(e as SignConfigBean)
                }
                if (mData.size > 0) {

                    viewBinder.mSignConfigGridView.numColumns = mData.size
                    viewBinder.mSignConfigGridView.adapter = mSignConfigAdapter
                    mSignConfigAdapter?.notifyDataSetChanged()
//                    setIsLoad(true)
                }
            }
        }
    }

    override fun lazyInit() {
        RestClient.builder()
            .url(R.string.sign_config)
            .success {
                parseSignConfig(it)
            }
            .failure {
                normalShortToast(_mActivity, R.string.net_work_failed)

            }.error { _, msg ->
                normalShortToast(_mActivity, msg)
            }
            .build().get()
    }

    private fun parseSignConfig(it: String?) {
        val mArray = JSON.parseArray(it, SignConfigBean::class.java)
        mData.clear()
        mData.addAll(mArray)
        mSignConfigAdapter?.updateList(mData)
        viewBinder.mSignConfigGridView.numColumns = mData.size
    }


}